import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, TextInput, Keyboard, NativeModules } from 'react-native';
import user from '@/api/user';
import { px2dp, fontColorCoffee } from '@/styles';
import { msg, SendMsgCode } from '@/common';

export default class InputCode extends Component {
  constructor(props) {
    super(props);
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { mobile, userInfo, routerFrom } = params;
    this.state = {
      code: false,
      begin: 0,
      user: {},
      Msg: '',
      keyShow: true,
      index: 0,
      mobile,
      routerFrom,
      userInfo
    };
  }

  componentDidMount() {
    const { mobile, routerFrom, userInfo } = this.state;
    const phoneNumber = routerFrom === 'setPwd' ? userInfo.wholeMobile : mobile;

    this.setState({
      mobile: phoneNumber
    }, () => {
      this.sendMsg();
    });

    user.getUserInfo().then(res => {
      console.log('短信验证码返回--》', res.data);
      if (res.success) {
        this.setState({ user: res.data });
      } else {
        msg.emit('app:loginTips', true);
      }
    });
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => this.setState({ keyShow: false }));
  }

  render() {
    const { mobile } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.paddingWrap}>
          <Text style={styles.tit}>输入验证码</Text>
          <View style={styles.tipWrap}>
            <Text style={styles.gray}>已发送4位验证码至：+86</Text>
            <Text style={styles.gray}>
              {' '}
              {mobile}
              {' '}
            </Text>
          </View>
          <View style={styles.flexB}>
            <TextInput
              style={styles.textInputMsg}
              ref='codeInput'
              maxLength={4}
              autoFocus
              caretHidden
              keyboardType='number-pad'
              onSubmitEditing={Keyboard.dismiss}
              blurOnSubmit
              defaultValue={this.state.Msg}
              onChangeText={(text) => {
                this.setState({ Msg: text });
              }}
            />
            {this._getInputItem()}
          </View>
          <View style={styles.marginLeft}>
            <SendMsgCode
              frameStyle={styles.frameStyle}
              count={60}
              changeWithCount={(count) => `${count}秒后重试`}
              activeTextStyle={{ color: fontColorCoffee }}
              id='verification'
              pressAction={this.sendMsg}
              ref={(e) => { this.countDownButton = e; }}
            />
          </View>
          <TouchableOpacity
            activeOpacity={1}
            style={
              this.state.Msg.length === 4 ?
                [styles.btnStyle, styles.focus] :
                [styles.btnStyle]
            }
            onPress={() => (this.state.Msg.length === 4 ? this._toPass() : {})}
          >
            <Text style={[styles.white, styles.confirm]}>验证</Text>
          </TouchableOpacity>
        </View>
      </View>

    );
  }

  _toPass = () => {
    const { mobile, routerFrom, userInfo } = this.state;
    const phoneNumber = routerFrom === 'setPwd' ? userInfo.wholeMobile : mobile;
    user.chekeCode({ mobile: phoneNumber, code: this.state.Msg }).then(res => {
      if (res.success) {
        this.setState({ begin: 0, Msg: '', index: 0 });
        msg.emit('router: goToNext', {
          routeName: 'SetPassword',
          mobile,
          routerFrom,
          userInfo
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 发送短信
  sendMsg = () => {
    const { mobile } = this.state;
    this.countDownButton.startCountDown(() => {
      user.getSmsCode({ mobile }).then(res => {
        if (!res.success) {
          NativeModules.WindowModule.showWindow({
            content: '验证码发送失败',
            onlyRightBtn: '1'
          }, (e) => { });
        }
      });
    });
  }

  _getInputItem = () => {
    const that = this;
    let inputItem = [];
    let { Msg } = this.state;
    // 理论上TextInput的长度是多少，这个i就小于它
    for (let i = 0; i < 4; i++) {
      inputItem.push(
        // i是从0开始的所以到最后一个框i的值是5
        // 前面的框的右边框设置为0，最后一个边框再将右边框加上
        <TouchableOpacity
          activeOpacity={1}
          key={i}
          style={i === 5 ? [styles.textInputView, { borderRightWidth: 1 }] : [styles.textInputView, { borderRightWidth: 0 }], Msg[i] ? [styles.textInputView, { borderColor: '#dbdbdb' }] : [styles.textInputView, { borderColor: '#f1f0ef' }]}
          onPress={() => {
            that.setState({ keyShow: true });
          }}
        >
          {i < Msg.length
            ? <Text style={{ fontSize: px2dp(48), color: '#333232' }}>{Msg[i]}</Text>
            : null}
        </TouchableOpacity>
      );
    }
    if (Msg.length === 4) {
      this.refs.codeInput.blur();
    }
    return inputItem;
  }

  UNSAFE_componentWillUnmount() {
    this.setState({ index: 0 });
    this.refs.codeInput.blur();
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFFFFF',
    height: '100%',
  },
  active: {
    color: '#BA914A',
    fontSize: px2dp(16)
  },
  disStyle: {
    color: '#999796',
    fontSize: px2dp(16)
  },
  frameStyle: {
    lineHeight: 60,
    backgroundColor: '#fff',
    color: 'red',
    borderWidth: 0,
    fontSize: 18,
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  marginLeft: {
    marginLeft: '60%'
  },
  paddingWrap: {
    padding: 30,
    paddingTop: px2dp(60)
  },
  tit: {
    fontSize: px2dp(48),
    color: '#333232',
  },
  tipWrap: {
    flexDirection: 'row',
    marginTop: px2dp(6)
  },
  Text: {
    color: '#999796'
  },
  white: {
    color: '#fff'
  },
  gray: {
    color: '#999796'
  },
  mobileColor: {
    color: '#333232'
  },
  btnStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(50),
    height: 48,
    margin: 'auto',
    marginTop: 40,
    backgroundColor: 'rgba(186, 145, 74, 0.5)'
  },
  focus: {
    backgroundColor: fontColorCoffee
  },
  textInputView: {
    height: 85 / 2,
    justifyContent: 'center',
    alignItems: 'center',
    flex: 1,
    borderBottomWidth: 1,
    borderColor: '#f1f0ef',
    marginRight: 24,
    backgroundColor: '#FFF',
    marginTop: px2dp(40)
  },
  textInputMsg: {
    zIndex: 10,
    position: 'absolute',
    width: '100%',
    height: 100 / 2,
    color: 'transparent',
    backgroundColor: 'transparent',
    top: px2dp(30),
  },
  flexB: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginLeft: px2dp(20),
  },
  confirm: {
    width: '100%',
    textAlign: 'center',
    height: 48,
    lineHeight: 48,
    fontSize: px2dp(32)
  }
});
